/*********************************************************************************
 *      Copyright:  (C) 2022 Zhang Changxing<ZhangChangxingVIP@163.com>
 *                  All rights reserved.
 *
 *       Filename:  ds18b20.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/13/2022)
 *         Author:  Zhang Changxing <ZhangChangxingVIP@163.com>
 *      ChangeLog:  1, Release initial version on "04/13/2022 01:26:26 AM"
 *                 
 ********************************************************************************/

#include "ds18b20.h"



/* Get temperature data for the Raspberry Pi ds18b20 */
int temperature(float *temp)
{
    DIR             *dir = NULL;
    struct  dirent  *drt = NULL;
    char            *string = NULL;
	int 			fd = -1;
	char			buf[512];
	char 			*str;
	char 			directory[100] = "/sys/bus/w1/devices/";
	uint8_t			*byte = NULL;

	if(NULL == temp)
	{
		log_error("The %s() argument incorrect!\n", __func__);
		return -1;
	}	

	if ((dir = opendir(directory)) == NULL)
	{
		log_error("Open directory %s failure:%s\n", directory, strerror(errno));
		return -2;
	}

	while ((drt = readdir(dir)) != NULL)
	{
		if (strstr(drt->d_name, "28-") != NULL)
		{
			string = drt->d_name;
			break;
		}
	}

	if (string == NULL)
	{
		log_error("Read directory name failure:%s\n", strerror(errno));
		return -3;
	}

	string = strcat(directory, string);
	string = strcat(directory, "/w1_slave");
	fd = open(string, O_RDONLY);
	if (fd < 0)
	{
		log_error("Open %s\n failure:%s\n", string, strerror(errno));
		return -4;
	}

	memset(buf, 0, sizeof(buf));
	if (read(fd, buf, sizeof(buf)) < 0)
	{
		log_error("Read data from w1_slave failure:%s\n", strerror(errno));
		close(fd);	
		return -5;
	}

	if ((str = strstr(buf, "t=")) == NULL)
	{
		log_error("Temperature not found:%s\n", strerror(errno));
		close(fd);	
		return -6;
	}

	str = str +2;
	*temp = atof(str)/1000;
	log_debug("The temperature is %f\n", *temp);
	close(fd);	
	return 0;
}



